<template>
  <el-form ref="updatePasswordFormRef" :model="updatePasswordForm" :rules="updatePasswordFormRules" label-position="top">
    <el-form-item label="旧密码" prop="password">
      <el-input v-model="updatePasswordForm.password" type="password" show-password clearable />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="updatePasswordForm.newPassword" type="password" show-password clearable />
    </el-form-item>
    <el-form-item label="再次输入新密码" prop="repetitionPassword">
      <el-input v-model="updatePasswordForm.repetitionPassword" type="password" show-password clearable />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {FormInstance} from "element-plus";
import {Response} from "@/entity/response";

const {userApi} = useApi();
const {logout} = useStores.user();
const updatePasswordFormRef = ref<FormInstance | undefined>();
const updatePasswordForm = reactive({
  password: "",
  newPassword: "",
  repetitionPassword: ""
});
const updatePasswordFormRules = {
  password: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  repetitionPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (updatePasswordForm.newPassword === updatePasswordForm.repetitionPassword) {
          callback();
        } else {
          callback(new Error('新密码 2 次输入的密码不一致'));
        }
      },
      trigger: "blur"
    }
  ]
};
const submitForm = () => {
  if (!updatePasswordFormRef.value) return;
  updatePasswordFormRef.value?.validate((valid) => {
    if (valid) {
      userApi.updatePassword(
          updatePasswordForm.password,
          updatePasswordForm.newPassword
      ).then((res: any) => {
        const {code}: Response = res;
        if (code === 200) {
          useUtils().ModalUtils.msgSuccess("密码修改成功");
          logout();
        }
      });
    } else {
      useUtils().ModalUtils.msgError("请填写正确的信息");
      return false;
    }
  })
}
defineExpose({
  submitForm
});
</script>

<style scoped lang="scss">
</style>